package com.itheima.contorller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.itheima.domain.User;
import com.itheima.service.Impl.UserServiceImpl;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
*   用于提供服务方法
* */
@WebServlet("/user/*")
public class UserServlet extends BasicSevlet{
    //创建json工具对象
    ObjectMapper mapper = new ObjectMapper();
    //创建服务层对象
    UserService service =new UserServiceImpl();

    //list方法 获取所有用户
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户列表
        List<User> userList = service.findAll();
        //将userList转换成json
        String json = mapper.writeValueAsString(userList);
        //System.out.println(json);
        //响应数据
        resp.getWriter().write(json);
    }

    //通过id删除方法
    private void delete(HttpServletRequest req, HttpServletResponse resp){
        //获取ids
        String ids = req.getParameter("ids");
        //System.out.println(ids);
        //调用业务层进行删除
        service.deleteByIds(ids);

    }


    //保存用户方法
    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取到用户数据
        String userJson = req.getParameter("user");
        //System.out.println(userJson);
        //将userJson转换成User对象
        User user = mapper.readValue(userJson, User.class);
        Integer changeLine = service.saveUser(user);

    }

    //通过id查找用户
    private void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取id
        String uid = req.getParameter("uid");
        //调用业务层方法返回用户对象
        User user = service.findById(uid);
        //将user转换成json
        String json = mapper.writeValueAsString(user);
        //把json响应给前端
        //System.out.println(json);
        resp.getWriter().write(json);
    }

    //通过id更新用户信息
    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取用户
        String userJson = req.getParameter("user");
        User user = new Gson().fromJson(userJson, User.class);
        System.out.println(user);
        //System.out.println(user);
        //转换成user对象
        //User user = mapper.readValue(userJson, User.class);
        //调用业务层方法更新用户数据
        service.update(user);
    }
}
